import { createRouter, createWebHashHistory } from "vue-router";
import routes from "./routes";
import { useKeepAliveViewStore } from "@/store/modules/keepAliveView";
import NProgress from "@/utils/progress";
import setPageTitle from "@/utils/set-page-title";
import { TOKEN_KEY } from "@/constants";
import { getStore } from "@/utils/storage";

const router = createRouter({
  history: createWebHashHistory(),
  routes
});

router.beforeEach((to, from, next) => {
  NProgress.start();
  // 路由缓存
  useKeepAliveViewStore().addKeepAliveView(to);
  setPageTitle(to.meta.title);

  const hasToken = getStore(TOKEN_KEY);

  if (hasToken) {
    if (to.path === "/login") {
      // 如果已登录，跳转到首页
      next({ path: "/" });
      NProgress.done();
    } else {
      // 获取用户信息
      next();
      NProgress.done();
    }
  } else {
    // 未登录
    if (!to.meta.auth) {
      next();
    } else {
      redirectToLogin(to, next);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});

/** 重定向到登录页 */
function redirectToLogin(to, next) {
  const params = new URLSearchParams(to.query);
  const queryString = params.toString();
  const redirect = queryString ? `${to.path}?${queryString}` : to.path;
  next(`/login?redirect=${encodeURIComponent(redirect)}`);
}

export default router;
